<?php
include_once dirname(__FILE__)."/template.ease.php";
include_once dirname(__FILE__)."/util.class.php";
include_once dirname(__FILE__)."/Tencent.php";
class func{
	private $db;
	private $log;
	private $default_page_size = 40;
	private $guest_uid=999;
	private $feed_type_upload = 0;
	private $feed_type_forward = 1;
	private $feed_type_comment = 2;
	private $config;
	function __construct($config,$db,$log){
		$this->config = $config;
		$this->db = $db;
		$this->log = $log;
	}
	
	public function check_brower(){
		$agent = $_SERVER[HTTP_USER_AGENT];
		if(strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 5") || strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 6") || strstr($_SERVER["HTTP_USER_AGENT"], "MSIE 7")){
			return "对不起，您的IE浏览器版本太低，请升级到IE8或IE9[".$_SERVER["HTTP_USER_AGENT"];
		}
		return null;
	}
	
	public function password_encode($password){
		return md5($password.$this->config[pwdkey]);
	}
	private function user_id_create(){
		$sql = "select max(uid) from t_user";
		$max_id = $this->db->query_first($sql);
		if(!$max_id){
			$max_id=20120000;
		}
		
		$pre = intval($max_id/100)+1;
		$next_id = $pre*100+rand(0, 99);
		return $next_id;
	}
	function createUser($email,$name,$password,$website,$mydesc){
		$password = $this->password_encode($password);
		$uid = $this->user_id_create();
		$sql = "insert into t_user(uid,email,name,password,website,mydesc,last_login,status) values('$uid','$email','$name','$password','$website','$mydesc',".time().",1)";
		if($this->db->update($sql)){
			return $uid;
		}else{
			return false;
		}
	}
	
	function getUserById($uid){
		$sql = "select * from t_user where uid='$uid'";
		return $this->db->query_assoc($sql);
	}
	function getFileById($fid){
		$sql = "select * from t_file a where a.fid='$fid'";
		return $this->db->query_assoc($sql);
	}
	function getResourceById($id){
		$sql = "select lx,fid,link from t_feed_resource where id='$id'";
		return $this->db->query_assoc($sql);
	}
	/**
	 * 登录系统，登陆成功返回用户信息，失败返回false.
	 * @param unknown_type $email
	 * @param unknown_type $passowrd
	 */
	function login($email,$password){
		if(!$email || !$password){
			return false;
		}
		$password = $this->password_encode($password);
		$sql = "select * from t_user where email='$email' and password='$password'";
		$user = $this->db->query_assoc($sql);
		$this->makeSession($user);
		return $user;
	}
	
	/**
	 * 讲用户登录信息记录到会话。
	 * @param unknown_type $user
	 */
	function makeSession($user){
		if($user){
			//保存用户信息到会话中并更新最后登陆时间。
			$sql = "update t_user set last_login=".time()." where uid=$user[uid]";
			$_SESSION["uid"]=$user[uid];
			$_SESSION["name"]=$user[name];
			$this->db->update($sql);
		}
	}
	function session_update($user){
			$_SESSION["uid"]=$user[uid];
			$_SESSION["name"]=$user[name];
	}
	/**
	 * 检查用户是否已经登录
	 */
	function validateLogin($msg = "请先登录"){
		if(!$_SESSION[uid] || !$_SESSION[name]){
			$this->redirect("login.php");
		}
	}
	function hasLogedIn(){
		return $_SESSION[uid] && $_SESSION[name];
	}
	function getUserByName($name){
		$sql = "select * from t_user where name='$name'";
		return $this->db->query_assoc($sql);
	}
	function getUserByEmail($email){
		$sql = "select * from t_user where email='$email'";
		return $this->db->query_assoc($sql);
	}
	function redirect($url){
		echo "<script language='javascript'>";
		echo "window.location.href='$url';";
		echo "</script>";
		die();
	}
	function redirect2($url){
		echo "<META HTTP-EQUIV=\"Refresh\" CONTENT=\"0; URL=$url\">";
	}
	function register_welcomemail($user,$smtpcfg,$weburl,$webname){
		$subject = $user[name].",".$webname."欢迎您";
		$html = "<p>亲爱的".$user[name]."，欢迎来到".$webname."</p>";
		$html = $html."<p>您的用户名为：".$user[name]."</p>";
		$html = $html."<p>您的邮箱为：".$user[email]."</p>";
		$html = $html."<p>如果您忘了密码，请到 ".$weburl." 重置密码</p>";
		$this->sendmail($smtpcfg[server],$smtpcfg[port],$smtpcfg[auth],$smtpcfg[name],$smtpcfg[password],$user[email],$subject,$html);
	}
	function register_confirmmail($user,$smtpcfg,$weburl,$webname){
		$key = $user[uid]."_".md5($user[uid].$user[password]);
		$subject = $webname."欢迎您，$user[name]";
		$html="<p>$user[name]，您好！</p>";
		$html = $html."<p>欢迎您注册".$webname."。</p>";
		$html = $html."<p>这是一份来自".$webname."的确认信，请点击以下链接激活您的账户：</p>";
		$html = $html."<p><a href='"."$weburl/register_confirm.php?key=$key"."'>点击此处激活您的账户</a></p>";
		$html = $html."<p>如果无法点击此链接，请复制一下链接地址到浏览器地址栏，打开页面即可：</p>";
		$html = $html."$weburl/register_confirm.php?key=$key";
		$this->sendmail($smtpcfg[server],$smtpcfg[port],$smtpcfg[auth],$smtpcfg[name],$smtpcfg[password],$user[email],$subject,$html);
	}
	function register_confirm($uid){
		$sql = "update t_user set status=1 where uid=$uid";
		return $this->db->update($sql);
	}
	
	function sendmail($server,$port,$auth,$name,$password,$to,$subject,$content,$mailtype="HTML"){
		$smtp = new smtp($server,$port,$auth,$name,$password);
		return $smtp->sendmail($to, $name,$subject,$content,$mailtype);
	}
	
	function error($errorCode,$msg= null){
		$tl = new template();
		$tl->set_var("code",$errorCode);
		$tl->set_var("msg",$msg);
		$tl->set_file("error");
		$tl->p();
		die();
	}
	
	function user_template($tl,$includePage="home"){
		global $includePage;
		$tl->set_file("u/template");
		$tl->p();
	}
	
	function getUploadedFiles($uid){
		$sql = "select a.fid,a.fname,a.uid,a.futime from t_user_file a,t_user b where a.uid=b.uid and a.uid=$uid order by a.futime desc";
		return $this->db->query_assoc_all($sql);
	}
	function incResourceDownload($id){
		$sql = "update t_feed_resource set download=download+1 where id='$id'";
		return $this->db->update($sql);
	}
	function allow_download($res_id,$client_ip,$allow_interval_in_seconds=60){
		$sql = "select count(*) from t_resource_download where res_id='$res_id' and client_ip='$client_ip' and now()-download_time<$allow_interval_in_seconds";
		$count = $this->db->query_first($sql);
		return $count==0;
	}
	function recordDownload($res_id,$uid,$client_ip){
		if($uid){
			$sql = "insert into t_resource_download(res_id,uid,download_time,client_ip) values('$res_id',$uid,now(),'$client_ip')";
		}else{
			$sql = "insert into t_resource_download(res_id,download_time,client_ip) values('$res_id',now(),'$client_ip')";
		}
		return $this->db->update($sql);
	}
	function downloadFile($filepath,$filename){
		$ua = $_SERVER["HTTP_USER_AGENT"];
		$filename = urlencode($filename);
		$filename = str_replace("+", "%20", $filename);
		if(file_exists($filepath)){
	       	$nFileSize=filesize ($filepath);
	       	header ("Content-type: application/octet-stream");
			if (preg_match("/Firefox/", $ua)) {
				header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"');
			}else{
				header ('Content-Disposition: attachment; filename=' . $filename);
			}
	       	header ("Accept-Ranges: bytes"); 
	       	header ("Content-Length: " . $nFileSize);
	       	readfile($filepath);
	   	}else{
	       	echo("文件不存在!");
	   	}
	}
	function search($q){
		$sql = "select * from t_user_file where fname like '%$q%' and fstatus<3";
		return $this->db->query_assoc_all($sql); 
	}
	function deleteUserFile($fid,$uid){
		$sql = "delete from t_user_file where fid='$fid' and uid='$uid'";
		return $this->db->update($sql);
	}
	
	
	/** 文件操作 */

	public function getBaseFileByMD5($md5){
		$sql = "select * from t_base_file where fmd5='$md5'";
		return $this->db->query_assoc($sql);
	}
	
	public function saveBaseFile($filedata){
		$tmpfile = $filedata["tmp_name"];
		
		/** 确保文件存在 */
		if(!file_exists($tmpfile)){
			$this->log->error("fle not exists");
			return false;
		}
		$mtime = filemtime($tmpfile);
		$size = $filedata["size"];
		
		/** 计算保存路径 */
		$fmd5 = md5_file($tmpfile);
		$savedir = $this->current_save_dir();
		$destfile_abs = $savedir[abs]."/".$fmd5;
		$destfile_rel = $savedir[rel]."/".$fmd5;
		
		/** 保存文件到文件系统 */
		if(!file_exists($destfile_abs)){
			$res = move_uploaded_file($tmpfile,$destfile_abs);
			if($res==false){
				$res = copy($tmpfile, $destfile_abs);
			}
			if($res==false){
				$this->log->log("保存文件到用户目录时出错！");
				return false;
			}
		}
		
		/** 保存文件信息到数据库t_base_file */
		$baseFile = $this->getBaseFileByMD5($fmd5);
		if(!$baseFile){
			$sql = "insert into t_base_file(`fmd5`,`size`,`mtime`,`path`) values('$fmd5',$size,$mtime,'".$destfile_rel."')";
			$res = $this->db->update($sql);
			if(!$res){
				return false;
			}
		}
		return $fmd5;
		
	}
	public function saveFile($uid,$filedata){
		if(!$uid){
			$uid = $this->guest_uid;
		}
		/*
		if(!$uid || !$filedata){
			$this->log->log("用户未登录或文件数据不存在！");
			return "用户未登录或文件数据不存在！";
		}
		*/
		$name = $filedata["name"];

		/* 保存文件 */
		$fmd5 = $this->saveBaseFile($filedata);
		if(!$fmd5){
			return false;
		}
		
		/* 关联文件与用户 */
		$file = $this->getFileByUidAndMD5($uid,$md5);	
		if(!$file){
			$upload_time = time();
			$fid = $this->id_create("file");
			$client_ip = $_SERVER[REMOTE_ADDR];
			$type = $filedata["type"];
			$size = $filedata["size"];
			$sql = "insert into t_file(fid,fmd5,uid,name,type,size,client_ip,upload_time) values('$fid','$fmd5',$uid,'$name','$type',$size,'$client_ip',$upload_time)";
			$res = $this->db->update($sql);
			if(!$res){
				return false;
			}
			return $fid;
		}else{
			return $file[fid];
		}
	}
	/*
	function upload($uid,$upload_name,$torrent_fid,$ed2k_link,$magnet_link,$thunder_link,$desc,$client_ip){
		$upload_name = addslashes($upload_name);
		$ed2k_link = addslashes($ed2k_link);
		$magnet_link = addslashes($magnet_link);
		$thunder_link = addslashes($thunder_link);
		$publish_time = time();
		$sql = "insert into t_msg(`uid`,`upload_name`,`type`,`torrent_fid`,`ed2k_link`,`magnet_link`,`thunder_link`,`desc`,`client_ip`,`publish_time`) values($uid,'$upload_name',$this->msg_type_upload,'$torrent_fid','$ed2k_link','$magnet_link','$thunder_link','$desc','$client_ip',$publish_time)";
		$this->db->update($sql);
		return $this->db->mysql_insert_id();
	}
	*/
	public function getFileRootDirectory(){
		$sql = "select value from t_sysconfig where `key`='file.rootdir'";
		return $this->db->query_first($sql);
	}

	function buildAvatarPath($fid){
		return dirname(__FILE__)."/../".$this->getFileRootDirectory()."/avatar/".$fid;
	}
	
	/**
	 * 计算当前文件保存的目录。
	 * <p>每次保存文件时，调用这个方法得到保存文件的位置。
	 * 计算方法：系统设置的根目录+‘yyyymm’格式的子目录。</p>
	 * @return 返回包含本地绝对路径和相对于网站根目录的相对路径。
	 */
	function current_save_dir(){
		$month = date('Ym',time());
		$dir_rel = $this->getFileRootDirectory()."/".$month;
		$dir_abs = dirname(__FILE__)."/../".$dir_rel;
			$this->createIndexFile($dir_abs);
		if(!is_dir($dir_abs)){
			mkdir($dir_abs);
		}
		return array('abs'=>$dir_abs,'rel'=>$dir_rel);
	}
	function createIndexFile($dir){
		if(file_exists($dir."/index.html"))return;

		$fp=fopen($dir."/index.html","w+");
		fputs($fp,"<script language='javascript'>window.location.href='".$this->config[weburl]."';</script>");
		fclose($fp);
	}
	function getFileURLByFID($fid){
		$file = $this->getFileById($fid);
		if(!$file){
			return "";
		}
		$basefile = $this->getBaseFileByMD5($file[fmd5]);
		return $this->config[weburl]."/".$basefile[path];
	}
	function getFilePathByFID($fid){
		$file = $this->getFileById($fid);
		if(!$file){
			return false;
		}
		$basefile = $this->getBaseFileByMD5($file[fmd5]);
		return dirname(__FILE__)."/../".$basefile[path];
	}
	/**
	 * 根据UID和MD5取得文件
	 * @param int $uid
	 * @param unknown_type $file
	 */
	private function getFileByUidAndMD5($uid,$md5){
		$sql = "select * from t_file where uid='$uid' and fmd5='$md5'";
		return $this->db->query_assoc($sql);
	}
	public function feed_uid($feed_id){
		return $this->db->query_first("select uid from t_feed where id='$feed_id'");
	}
	public function getFeedDetail($feed_id){
		if(!$feed_id)return null;
		$sql = "select a.id,a.uid,b.avatar_fid_m,a.lx,a.msg,a.tags,a.like,a.publish_time,a.refer_id,a.forward,a.comment,b.name uname from t_feed a,t_user b where a.uid=b.uid and a.id='$feed_id'";
		$feed = $this->db->query_assoc($sql);
		if($feed){
			if($feed[tags]){
				$feed[tags] = explode(" ", $feed[tags]);
			}
			$feed[publish_time] = $this->calc_publish_time($feed[publish_time]);
			
			if($feed[lx]==0){
				//resources
				$sql2 = "select id,lx,name,fid,link,round(size/1024,2) size,download from t_feed_resource where feed_id='$feed[id]'";
				$reslist = $this->db->query_assoc_all($sql2);
				if($reslist){
					for($i=0;$i<count($reslist);$i++){
						if($reslist[$i][size]){
							$reslist[$i][size] = $this->cal_size($reslist[$i][size]);
						}
					}
					$feed[reslist]=$reslist;
				}
				//pics
				$sql3 = "select id,pic_fid,pic_name,pic_thumb_fid from t_feed_pic where feed_id='$feed[id]'";
				$piclist = $this->db->query_assoc_all($sql3);
				if($piclist){
					foreach ($piclist as $k=>$pic){
						$piclist[$k][url]=$this->getFileURLByFID($pic[pic_fid]);
						$piclist[$k][url_thumb]=$this->getFileURLByFID($pic[pic_thumb_fid]);
						$thumbpath = $this->getFilePathByFID($pic[pic_thumb_fid]);
						if(file_exists($thumbpath)){
							$thumbsize = getimagesize($thumbpath);
						}
						if($thumbsize){
							$piclist[$k][thumb_h]=100;
							$piclist[$k][thumb_w]=$thumbsize[0]*100/$thumbsize[1];
						}else{
							$piclist[$k][thumb_w]=100;
							$piclist[$k][thumb_h]=50;
						}
						
					}
					$feed[piclist]=$piclist;
				}
			}elseif($feed[lx]==1){
				if($feed[refer_id]){
					$refer = $this->getFeedDetail($feed[refer_id]);
					if($refer){
						$feed[refer]=$refer;
					}
				}
			}
		}
		return $feed;
	}
	public function user_follow_count($uid){
		$sql = "select count(*) from t_follower a,t_user b where a.uid=b.uid and a.follower_uid='$uid'";
		return $this->db->query_first($sql);
	}
	/**
	 * 获取关注的人的信息
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pagesize
	 */
	public function user_follow($uid,$page=1,$pagesize=20){
		$from = ($page-1)*$pagesize;
		$sql = "select a.uid,a.ftime,b.name,b.website,b.mydesc,b.avatar_fid_m from t_follower a,t_user b where a.uid=b.uid and a.follower_uid='$uid' order by a.ftime desc limit $from,$pagesize";
		$presons = $this->db->query_assoc_all($sql);
		if($presons){
			for($i=0;$i<count($presons);$i++){
				$person  = $presons[$i];
				//get relations
				$presons[$i][relation]=$this->getRelation($person[uid]);
			}
		}
		return $presons;
	}
	public function user_fans_count($uid){
		$sql = "select count(*) from t_follower a,t_user b where a.uid=b.uid and a.uid='$uid'";
		return $this->db->query_first($sql);
	}
	/**
	 * 获取粉丝的信息
	 * @param unknown_type $uid
	 * @param unknown_type $page
	 * @param unknown_type $pagesize
	 */
	public function user_fans($uid,$page=1,$pagesize=20){
		$from = ($page-1)*$pagesize;
		$sql = "select a.follower_uid uid,a.ftime,b.name,b.website,b.mydesc,b.avatar_fid_m from t_follower a,t_user b where a.follower_uid=b.uid and a.uid='$uid' order by a.ftime desc limit $from,$pagesize";
		$presons = $this->db->query_assoc_all($sql);
		if($presons){
			for($i=0;$i<count($presons);$i++){
				$person  = $presons[$i];
				//get relations
				$presons[$i][relation]=$this->getRelation($person[uid]);
			}
		}
		return $presons;
	}
	public function getFeeds($uid,$page=1,$pagesize=20){
		$from = ($page-1)*$pagesize;
		$sql = "select a.id from t_feed a where a.uid='$uid' and a.lx in (0,1) order by a.publish_time desc limit $from,$pagesize";
		$idlist = $this->db->query_first_all($sql);
		$feeds = array();
		foreach ($idlist as $id){
			array_push($feeds,$this->getFeedDetail($id));
		}
		return $feeds;
	}
	public function getFeedsCount($uid = false){
		if($uid){
			$sql = "select count(*) from t_feed a where a.uid='$uid' and a.lx in (0,1) order by a.publish_time";
		}else{
			$sql = "select count(*) from t_feed a where a.lx in (0,1) order by a.publish_time";
		}
		return $this->db->query_first($sql);
	}
	public function getTimeline($uid,$page=1,$pagesize=20){
		$from = ($page-1)*$pagesize;
		$sql = "select a.id from t_feed a where a.lx in (0,1) and (a.uid='$uid' or a.uid in (select uid from t_follower where follower_uid='$uid')) order by a.publish_time desc limit $from,$pagesize";
		$idlist = $this->db->query_first_all($sql);
		$feeds = array();
		foreach($idlist as $id){
			array_push($feeds,$this->getFeedDetail($id));
		}
		return $feeds;
	}
	public function getTimelineCount($uid){
		$sql = "select count(*) from t_feed a where a.lx in (0,1) and (a.uid='$uid' or a.uid in (select uid from t_follower where follower_uid='$uid')) order by a.publish_time";
		return $this->db->query_first($sql);
	}
	public function getRelation($uid){
		$sql = "select count(follower_uid) from t_follower where uid='$uid'";
		$folllowers = $this->db->query_first($sql);
		$sql = "select count(uid) from t_follower where follower_uid='$uid'";
		$following = $this->db->query_first($sql);
		$sql = "select count(*) from t_feed where uid='$uid' and lx in ('0','1')";
		$feeds = $this->db->query_first($sql);
		$arr = array('follow'=>$following,'fans'=>$folllowers,'feeds'=>$feeds);
		return $arr;
	}
	private function feed_id_create(){
		$sql = "select max(id) from t_feed";
		$max_id = $this->db->query_first($sql);
		$sql = "select max(id) from t_feed_deleted";
		$max_id_deleted = $this->db->query_first($sql);
		if($max_id){
			if($max_id_deleted && $max_id_deleted>$max_id){
				$max_id = $max_id_deleted;
			}
			if($max_id<100){
				$max_id=$max_id*100;
			}
		}
		if(!$max_id){
			$max_id = 1000100;
		}
		$pre = intval($max_id/100)+1;
		$next_id = $pre*100+rand(0, 99);
		return $next_id;
	}
	public function save_feed_resource($uid,$desc,$tags,$client_ip){
		$desc = trim(addslashes($desc));
		$tags = trim(addslashes($tags));
		if($tags){
			$arr_tags = explode(" ", $tags);
			$arr2_targs = array();
			foreach ($arr_tags as $tag){
				if(strlen(trim($tag))>0){
					array_push($arr2_targs,trim($tag));
				}
			}
			$tags = implode(" ", $arr2_targs);
		}
		$feed_id = $this->feed_id_create();
		$sql = "insert into t_feed(`id`,`uid`,`lx`,`msg`,`tags`,`client_ip`,`publish_time`) values('$feed_id','$uid',0,'$desc','$tags','$client_ip',".time().")";
		if($this->db->update($sql)){
			return $feed_id; 
		}else{
			return false;
		}
	}
	public function save_feed_resource_torrent($feed_id,$name,$fid,$size){
		$id = $this->id_create("torrent");
		$name = addslashes($name);
		$sql = "insert into t_feed_resource(id,feed_id,lx,name,fid,size,download) values('$id',$feed_id,'torrent','$name','$fid',$size,0)";
		return $this->db->update($sql);
	}
	public function save_feed_resource_pic($feed_id,$name,$fid,$size,$fid_thumb){
		$id = $this->id_create("pic");
		$name = addslashes($name);
		$sql = "insert into t_feed_pic(id,feed_id,pic_fid,pic_name,pic_size,pic_thumb_fid,publish_time) values('$id',$feed_id,'$fid','$name',$size,'$fid_thumb',".time().")";
		return $this->db->update($sql);
	}
	public function save_feed_resource_link($feed_id,$lx,$name,$link){
		$id = $this->id_create($lx);
		$sql = "";
		$name = addslashes($name);
		$link = addslashes($link);
		if($lx=='ed2k'){
			$size = $this->ed2k_size($link);
			$sql = "insert into t_feed_resource(id,feed_id,lx,name,link,size,download) values('$id',$feed_id,'$lx','$name','$link',$size,0)";
		}else{
			$sql = "insert into t_feed_resource(id,feed_id,lx,name,link,download) values('$id',$feed_id,'$lx','$name','$link',0)";
		}
		return $this->db->update($sql);
	}
	public function ed2k_size($ed2k_link){
		if($ed2k_link){
			$arr = explode("|",$ed2k_link);
			if(count($arr)>=4){
				return $arr[3];
			}
		}
		return 0;
	}
	public function cal_size($kb){
		$g = 1024*1024;
		$m = 1024;
		if($kb){
			if($kb>$g){
				return round($kb/$g,2)."GB";
			}else if($kb > $m){
				return round($kb/$m,2)."MB";
			}else{
				return $kb."KB";
			}
		}else{
			return "0B";
		}
	}
	public function follow($follow_id,$follower_id){
		if($follow_id && $follower_id && $follow_id!=$follower_id){
			$sql = "insert into t_follower(uid,follower_uid,ftime) values($follow_id,$follower_id,now())";
			return $this->db->update($sql);
		}
	}
	public function unfollow($follow_id,$follower_id){
		if($follow_id && $follower_id && $follow_id!=$follower_id){
			$sql = "delete from t_follower where uid='$follow_id' and follower_uid='$follower_id'";
			return $this->db->update($sql);
		}
	}
	public function has_followed($follow_id,$follower_uid){
		if($follow_id && $follower_uid){
			$sql = "select count(*) from t_follower where uid='$follow_id' and follower_uid='$follower_uid'";
			$res = $this->db->query_first($sql);
			if($res){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	public function calc_publish_time($publish_time){
		$int_publish = $publish_time;//$this->date_string_to_int($publish_time);
		$arr_publish = $this->date_int_to_array($int_publish);
		$int_now = time();
		$arr_now = $this->date_int_to_array($int_now);
		if($arr_publish[year]<$arr_now[year]){
				return $arr_publish[year]."年".$arr_publish[mon]."月".$arr_publish[mday]."日&nbsp;".$arr_publish[hours].":".$arr_publish[minutes];
		}else if($arr_publish[mon]<$arr_now[mon] || $arr_publish[mday]<$arr_now[mday]){
			return $arr_publish[mon]."月".$arr_publish[mday]."日&nbsp;".$arr_publish[hours].":".$arr_publish[minutes];
		}else{
			if($int_now-$int_publish<=60){
				return (int)($int_now-$int_publish)."秒前";
			}elseif ($int_now-$int_publish<=60*60){
				return (int)(($int_now-$int_publish)/60)."分钟前";
			}else{
				return (int)(($int_now-$int_publish)/(60*60))."小时前";
			}
		}
		return $publish_time;
	}
	
	public function feeds_keywords($feeds){
		$keyword = '';
		if($feeds && count($feeds)>0){
			foreach($feeds as $feed){
				if($feed && $feed[tags]){
					if($keyword==''){
						$keyword.=implode(',', $feed[tags]);
					}else{
						$keyword.=','.implode(',', $feed[tags]);
					}
				}
			}
		}
		$keyword = util::substr($keyword, 0, 50);
		return $keyword;
	}
	public function feeds_description($feeds){
		$desc = '';
		if($feeds && count($feeds)>0){
			foreach ($feeds as $feed){
				if($feed[reslist]){
					if($desc!=''){
						$desc.=';';
					}
					$desc.=$feed[reslist][0][name];
					if($feed[msg]){
						$desc.=':'.$feed[msg];
					}
				}
			}
		}
		return util::substr($desc, 0, 100);
	}
	/* explore.php */
	public function getRecentFeeds($page,$pagesize){
		$from = ($page-1)*$pagesize;
		$sql = "select id from t_feed where lx in('0','1') order by publish_time desc limit $from,$pagesize";
		$idlist = $this->db->query_first_all($sql);
		$feeds = array();
		foreach($idlist as $id){
			array_push($feeds,$this->getFeedDetail($id));
		}
		return $feeds;
	}
	/* resetpwd.php */
	public function resetpwd_vkey_create($uid){
		$res = $this->resetpwd_vkey_delete($uid);
		if($res){
			$vkey = $this->id_create("vkey");
			$sql = "insert into t_resetpwd(uid,vkey,rq) values($uid,'$vkey',".time().")";
			if($this->db->update($sql)){
				return $vkey;
			}
		}
		return false;
	}
	public function resetpwd_vkey_delete($uid){
		$sql = "delete from t_resetpwd where uid='$uid'";
		return $this->db->update($sql);
	}
	public function mail_resetpwd($user,$vkey,$smtpcfg,$weburl,$webname){
		$subject = "重置您在".$webname."的密码";
		$url = $weburl."/resetpwd.php?vkey=".$user[uid]."_".$vkey;
		$html = "<p>亲爱的".$user[name]."：</p>";
		$html .= "<p>您的重置密码请求已经通过审核，请点击以下链接进入充值密码页面：</p>";
		$html .= "<p><a href='".$url."'>".$url."</a></p>";
		$html .= "<p>感谢您对".$webname."的支持！</p>";
		$html .= "<p>".$webname."&nbsp;&nbsp;<a href='".$weburl."'>".$weburl."</a></p>";
		return $this->sendmail($smtpcfg[server],$smtpcfg[port],$smtpcfg[auth],$smtpcfg[name],$smtpcfg[password],$user[email],$subject,$html);
	}
	
	public function v_resetpwd($uid,$vkey){
		$sql = "select count(*) from t_resetpwd where uid='$uid' and vkey='$vkey'";
		return $this->db->query_first($sql);
	}
	
	public function user_set_password($uid,$pwd){
		if($uid && $pwd){
			$pwd = $this->password_encode($pwd);
			$sql = "update t_user set password='$pwd' where uid='$uid'";
			return $this->db->update($sql);
		}
		return false;
	}
	
	public function feed_delete($uid,$feed_id){
		if($uid && $feed_id){
			$sql = "select count(*) from t_feed where id='$feed_id' and $uid='$uid'";
			$res = $this->db->query_first($sql);
			if($res>0){
				$sql = "insert into t_feed_deleted select * from t_feed where id='$feed_id' and uid='$uid'";
				$res = $this->db->update($sql);
				if($res){
					$sql = "delete from t_feed where id='$feed_id' and uid='$uid'";
					return $this->db->update($sql);
				}
			}
		}
		return false;
	}
	public function profile_validate_field($user,$email,$name,$website,$mydesc){
		//验证邮箱
		$email = strtolower($email);
		if(!$email){
			$e_email="邮箱地址未填写";
		}elseif(!util::validateEmail($email)){
			$e_email="邮箱地址格式不正确";
		}else{
			$user2 = $this->getUserByEmail($email);
			if($user2 && $user2[uid]!=$user[uid]){
				$e_email="该邮箱已被注册";
			}
		}
		//验证昵称
		if(!$name){
			$e_name="昵称不能为空";
		}elseif(util::length($name)<2 || util::length($name)>10){
			$e_name="可输入2到10个字符";
		}else{
			$user2 = $this->getUserByName($name);
			if($user2 && $user2[uid]!=$user[uid]){
				$e_name="该昵称已被注册";
			}
		}
		//验证网址
		if($website){
			$e_website = util::validateURL($website);
			if(!$e_website){
				$e_website = "无效的网址格式，请以http(s)://开头";
			}else{
				unset($e_website);
			}
		}
		//验证自我介绍
		if($mydesc){
			if(util::length($mydesc)>70){
				$e_mydesc = "字数太多了，不超过70个";
			}
		}
		$res = array();
		if($e_email){
			$res[e_email]=$e_email;
		}
		if($e_name){
			$res[e_name]=$e_name;
		}
		if($e_website){
			$res[e_website]=$e_website;
		}
		if($e_mydesc){
			$res[e_mydesc]=$e_mydesc;
		}
		return $res;
	}
	public function profile_update($user,$email,$name,$website,$mydesc){
		if($user && $email && $name){
			$sql = "update t_user set email='$email',name='$name',website='$website',mydesc='$mydesc' where uid='$user[uid]'";
			$res = $this->db->update($sql);
			if($res){
				$this->session_update($user);
				return true;
			}
		}
		return false;
	}
	
	/** 微博同步 */
	public function oauth_tencent_info_get($uid){
		if($uid){
			$sql = "select * from t_oauth_tencent where uid='$uid'";
			return $this->db->query_assoc($sql);
		}else{
			return false;
		}
	}
	public function oauth_tencent_info_save($uid,$info){
		$this->db->update("delete from t_oauth_tencent where uid='$uid'");
		
		$sql = "insert into t_oauth_tencent(uid,access_token,refresh_token,expires_in,code,openid,openkey,username,nickname,ctime)";
		$sql .= " values('$uid','$info[access_token]','$info[refresh_token]','$info[expires_in]','$info[code]','$info[openid]','$info[openkey]','$info[name]','$info[nick]',".time().")";
		
		return $this->db->update($sql);
	}
	public function oauth_tencent_info_makesession($uid){
		$info = $this->oauth_tencent_info_get($uid);
		if($info){
			$_SESSION['t_access_token'] = $info['access_token'];
	        $_SESSION['t_refresh_token'] = $info['refresh_token'];
	        $_SESSION['t_expire_in'] = $info['expire_in'];
	        $_SESSION['t_code'] = $info['code'];
	        $_SESSION['t_openid'] = $info['openid'];
	        $_SESSION['t_openkey'] = $info['openkey'];
		}
        
	}
	public function oauth_tencent_info_delete($uid){
		return $this->db->update("delete from t_oauth_tencent where uid='$uid'");
	}
	
	/**
	 * 将资源发布到关联的腾讯微博
	 * @param unknown_type $uid
	 * @param unknown_type $feed_id
	 */
	public function oauth_tencent_publish($uid,$feed_id){
		if($uid && $feed_id){
			$feed = $this->getFeedDetail($feed_id);
			if($feed){
				$content = $this->share_content($feed);
				if($content){
					$this->oauth_tencent_info_makesession($uid);
					
					$param = array(
						format=>"json",
						content=>$content." 点击下载 ".$this->config[weburl]."/u.php?feed=$feed_id",
						clientip=>Common::getClientIp()
					);
					
					if($feed[refer]){
						$feed = $feed[refer];
					}
					if($feed[piclist] && count($feed[piclist])>0){
						$command = "t/add_pic_url";
						$param[pic_url]=$this->getFileURLByFID($feed[piclist][0][pic_fid]);
					}else{
						$command = "t/add";
					}
					return json_encode(Tencent::api($command,$param,'POST'));
				}
			}else{
				$this->log->debug("feed不存在");
			}
		}else{
			$this->log->debug("没有uid或feedid");
		}
		return false;
	}
	public function avatar_update($uid,$avatar_fid,$avatar_fid_m,$avatar_fid_s){
		$sql = "update t_user set avatar_fid='$avatar_fid',avatar_fid_m='$avatar_fid_m',avatar_fid_s='$avatar_fid_s' where uid='$uid'";
		return $this->db->update($sql);
	}
	public function register_validate_field($email,$name,$pwd,$website,$mydesc){
		//验证邮箱
		$email = strtolower($email);
		if(!$email){
			$e_email="邮箱地址未填写";
		}elseif(!util::validateEmail($email)){
			$e_email="邮箱地址格式不正确";
		}elseif($this->getUserByEmail($email)){
			$e_email="该邮箱已被注册";
		}
		//验证昵称
		if(!$name){
			$e_name="昵称不能为空";
		}elseif(util::length($name)<2 || util::length($name)>10){
			$e_name="可输入2到10个字符";
		}elseif($this->getUserByName($name)){
			$e_name="该昵称已被注册";
		}
		//验证密码
		if(!$pwd){ 
			$e_pwd = "密码不能为空";
		}else{
			$pwd_res = $this->v_password($pwd);
			if($pwd_res===true){
			}else{
				$e_pwd = $pwd_res;
			}
		}
		//验证网址
		if($website){
			$e_website = util::validateURL($website);
			if(!$e_website){
				$e_website = "无效的网址格式，请以http(s)://开头";
			}else{
				unset($e_website);
			}
		}
		//验证自我介绍
		if($mydesc){
			if(util::length($mydesc)>70){
				$e_mydesc = "字数太多了，不超过70个";
			}
		}
		$res = array();
		if($e_email){
			$res[e_email]=$e_email;
		}
		if($e_name){
			$res[e_name]=$e_name;
		}
		if($e_pwd){
			$res[e_pwd]=$e_pwd;
		}
		if($e_website){
			$res[e_website]=$e_website;
		}
		if($e_mydesc){
			$res[e_website]=$e_mydesc;
		}
		return $res;
	}
	public function image_type($path_img){
		$image_type = 0;
		switch (exif_imagetype($path_img)) {
		    case IMAGETYPE_GIF:
		        $image_type = IMG_GIF;
		        break;
		    case IMAGETYPE_JPEG:
		        $image_type = IMG_JPG;
		        break;
		    case IMAGETYPE_JPEG2000:
		        $image_type = IMG_JPG;
		        break;
		    case IMAGETYPE_PNG:
		        $image_type = IMG_PNG;
		        break;
		    case IMAGETYPE_WBMP:
		        $image_type = IMG_WBMP;
		        break;
			default:
		        $image_type = 0;
		        break;
		}
		return $image_type;
	}
	
	public function image_type_to_content_type($imagetype){
		$content_type = "";
		switch($imagetype){
			case IMG_GIF:
				$content_type = "image/gif";
				break;
			case IMG_JPG:
				$content_type = "image/jpeg";
				break;
			case IMG_PNG:
				$content_type = "image/png";
				break;
			case IMG_WBMP:
				$content_type = "image/x-ms-bmp";
				break;
			default:
				$content_type = "";
		}
		return $content_type;
	}
	public function image_content_type($path_img){
		switch (exif_imagetype($path_img)) {
		    case IMAGETYPE_GIF:
		        $image_type = "image/gif";
		        break;
		    case IMAGETYPE_JPEG:
		        $image_type = "image/jpeg";
		        break;
		    case IMAGETYPE_PNG:
		        $image_type = "image/png";
		        break;
		    case IMAGETYPE_WBMP:
		        $image_type = "image/x-ms-bmp";
		        break;
			default:
		        $image_type = null;
		        break;
		}
		return $image_type;
	}
	
	public function feed_comments_count($feed_id){
		$sql = "select count(*) from t_feed where refer_id='$feed_id' and lx='2'";
		return $this->db->query_first($sql);
	}
	public function feed_comments($feed_id,$page=1,$pagesize=10){
		$from = ($page-1)*$pagesize;
		$sql = "select a.id,b.uid,b.name uname,a.msg,b.avatar_fid_s,a.publish_time from t_feed a, t_user b where a.uid=b.uid and a.refer_id='$feed_id' and a.lx='2' order by a.publish_time desc limit $from,$pagesize";
		return $this->db->query_assoc_all($sql);
	}
	public function feed_comment_add($uid,$refer_id,$comment){
		if($uid && $refer_id && strlen($comment)>0){
			$comment = addslashes($comment);
			$feed_id = $this->feed_id_create();
			$client_ip = $_SERVER[REMOTE_ADDR];
			$sql = "insert into t_feed(`id`,`uid`,`lx`,`msg`,`refer_id`,`client_ip`,`publish_time`) values('$feed_id','$uid',2,'$comment','$refer_id','$client_ip',".time().")";
			if($this->db->update($sql)){
				$sql = "update t_feed set comment=comment+1 where id='$refer_id'";
				if($this->db->update($sql)){
					return $feed_id; 
				}
			}
		}
		return false;
	}
	public function feed_forward_add($uid,$refer_id,$msg){
		if($uid && $refer_id){
			$msg = addslashes($msg);
			$feed_id = $this->feed_id_create();
			$client_ip = $_SERVER[REMOTE_ADDR];
			
			$sql = "insert into t_feed(id,uid,lx,msg,refer_id,client_ip,publish_time) values('$feed_id','$uid','1','$msg','$refer_id','$client_ip',".time().")";
			if($this->db->update($sql)){
				$sql = "update t_feed set forward=forward+1 where id='$refer_id'";
				if($this->db->update($sql)){
					return $feed_id; 
				}
			}
		}
		return false;
	}
	public function feed_comment_delete($comment_id,$uid){
		$sql = "select refer_id from t_feed where id='$comment_id' and uid='$uid' and lx='2'";
		$refer_id = $this->db->query_first($sql);
		if($refer_id){
			$sql = "delete from t_feed where id='$comment_id' and uid='$uid' and lx='2'";
			$res =  $this->db->update($sql);
			if($res){
				$sql = "update t_feed set comment=comment-1 where id='$refer_id'";
				return $this->db->update($sql);
			}
		}else{
			return "评论不存在";
		}
	}
	
	public function share_record($feed_id,$uid,$client_ip,$webid){
		if($uid){
			$res = $this->db->update("insert into t_share(feed_id,share_ip,share_uid,webid,share_time) values('$feed_id','$client_ip','$uid','$webid',now())");
		}else{
			$res = $this->db->update("insert into t_share(feed_id,share_ip,webid,share_time) values('$feed_id','$client_ip','$webid',now())");
		}
		if($res){
			return $this->db->mysql_insert_id();
		}else{
			return false;
		}
	}
	
	public function share_content($feed){
		if(!$feed){
			return "";
		}
		
		if ($feed[refer]){
			$feed = $feed[refer];
		}

		$title = "";
		if($feed[reslist] && count($feed[reslist])>0){
			if(count($feed[reslist])==1){
				$title = $feed[reslist][0][name];
			}else{
				foreach ($feed[reslist] as $k=>$res){
					$title.=" （".($k+1)."）".$res[name];
				}
			}
		}
		
		if(!$title){
			$title = $feed[msg];
		}
		if(util::length($title)>90){
			$title = "#比特圈资源分享# ".util::substr($title, 0,120)."。。。";
		}else{
			$title = "#比特圈资源分享# ".$title;
		}
		return $title;
	}
	
	public function log_pageview(){
		$uid = $_SESSION[uid];
		$client_ip = $_SERVER[REMOTE_ADDR];
		$request_uri = addslashes($_SERVER[REQUEST_URI]);
		
		if(strstr($request_uri, "a.php") 
			|| strstr($request_uri, "/feeds.php") 
			|| strstr($request_uri, "/share.php") 
			|| strstr($request_uri, "/login.php") 
			|| strstr($request_uri, "/logout.php")){
			return;
		}
		if($uid){
			$res = $this->db->update("insert into t_pageview(page,client_ip,view_time,uid) values('$request_uri','$client_ip',now(),'$uid')");
		}else{
			$res = $this->db->update("insert into t_pageview(page,client_ip,view_time) values('$request_uri','$client_ip',now())");
		}
	}
	
	public function search_resource_count($key,$lx,$sj){
		$key = trim(addslashes($key));
		$key = str_replace("/", "//", $key);
		$key = str_replace("%", "/%", $key);
		
		if($lx=='torrent'){
			$where_lx = "and b.lx='torrent'";
		}elseif($lx=='ed2k'){
			$where_lx = "and b.lx='ed2k'";
		}elseif($lx=='magnet'){
			$where_lx = "and b.lx='magnet'";
		}elseif($lx=='thunder'){
			$where_lx = "and b.lx='thunder'";
		}else{
			$where_lx = "";
		}
		
		if($sj=='1' || $sj=='3' || $sj=='7'){
			$where_sj = "and subdate(now(),interval $sj day)<publish_time";
		}else{
			$where_sj = "";
		}
		
		$sql = "select count(distinct a.id) from t_feed a,t_feed_resource b where a.id=b.feed_id and a.lx='0' and (a.msg like '%$key%' or a.tags like '%$key%' or b.name like '%$key%' escape '/') $where_lx $where_sj";
		return $this->db->query_first($sql);
	}
	public function search_resource($key,$lx,$sj,$page,$pagesize){
		$from = ($page-1)*$pagesize;
		$key = trim(addslashes($key));
		$key = str_replace("/", "//", $key);
		$key = str_replace("%", "/%", $key);
		
		if($lx=='torrent'){
			$where_lx = "and b.lx='torrent'";
		}elseif($lx=='ed2k'){
			$where_lx = "and b.lx='ed2k'";
		}elseif($lx=='magnet'){
			$where_lx = "and b.lx='magnet'";
		}elseif($lx=='thunder'){
			$where_lx = "and b.lx='thunder'";
		}else{
			$where_lx = "";
		}
		
		if($sj=='1' || $sj=='3' || $sj=='7'){
			$where_sj = "and subdate(now(),interval $sj day)<publish_time";
		}else{
			$where_sj = "";
		}
		
		$sql = "select distinct a.id from t_feed a,t_feed_resource b where a.id=b.feed_id and a.lx='0' and (a.msg like '%$key%' or a.tags like '%$key%' or b.name like '%$key%' escape '/') $where_lx $where_sj order by a.publish_time desc limit $from,$pagesize";
		$idlist = $this->db->query_first_all($sql);
		$feeds = array();
		foreach ($idlist as $id){
			array_push($feeds, $this->getFeedDetail($id));
		}
		return $feeds;
	}
	
	public function qiu_create($zymc,$zysm,$tzyx){
		$zymc = addslashes($zymc);
		$zysm = addslashes($zysm);
		$tzyx = addslashes($tzyx);
		$id = $this->id_create("qiu");
		$sql = "insert into qiu_post(id,zymc,zysm,tzyx,post_time) values('$id','$zymc','$zysm','$tzyx',".time().")";
		return $this->db->update($sql);
	}
	
	public function qiu_query_count(){
		$sql = "select count(*) from qiu_post";
		return $this->db->query_first($sql);
	}
	public function qiu_query($page,$pagesize){
		$from = ($page-1)*$pagesize;
		$sql = "select * from qiu_post order by post_time desc limit $from,$pagesize";
		$posts = $this->db->query_assoc_all($sql);
		foreach ($posts as $k=>$post){
			$replys = $this->qiu_replys_get($post[id]);
			if($replys && count($replys)>0){
				$posts[$k][replys]=$replys;
			}
		}
		return $posts;
	}
	
	public function qiu_get($qiu_id){
		$sql = "select * from qiu_post where id='$qiu_id'";
		$post = $this->db->query_assoc($sql);
		
		if($post){
			$replys = $this->qiu_replys_get($post[id]);
			if($replys && count($replys)>0){
				$post[replys]=$replys;
			}
		}
		
		return $post;
	}
	
	public function qiu_replys_get($qiu_id){
		$sql = "select id,qiu_id,lx,fid,link,fname,round(fsize/1024,2) fsize,ly,mail,download,publish_time from qiu_reply where qiu_id='$qiu_id' order by publish_time desc";
		return $this->db->query_assoc_all($sql);
	}
	
	public function qiu_reply($qiu_id,$lx,$fid,$link,$fname,$fsize,$ly,$mail){
		$link = addslashes($link);
		$fname = addslashes($fname);
		$ly = addslashes($ly);
		$id = $this->id_create("qiu_reply");
		$sql = "insert into qiu_reply(id,qiu_id,lx,fid,link,fname,fsize,ly,mail,publish_time) values('$id','$qiu_id','$lx','$fid','$link','$fname',$fsize,'$ly','$mail',".time().")";
		if($this->db->update($sql)){
			return $id;
		}else{
			return null;
		}
	}
	
	public function qiu_get_reply($reply_id){
		return $this->db->query_assoc("select id,qiu_id,lx,fid,link,fname,round(fsize/1024,2) fsize,ly,mail,download,publish_time from qiu_reply where id='$reply_id'");
	}
	
	public function qiu_incDownload($reply_id){
		return $this->db->update("update qiu_reply set download=download+1 where id='$reply_id'");
	}
	
	public function qiu_notify($qiu_id,$reply_id,$config){
		$qiu_mail = $this->db->query_first("select tzyx from qiu_post where id='$qiu_id'");
		$reply_mail = $this->db->query_first("select mail from qiu_reply where id='$reply_id'");
		if($qiu_mail){
			$subject = "您在".$config[webname]."发布的一个资源请求有了一个新回复";
			
			$html = "<p>亲爱的用户，您好！<p>";
			$html .="<p>您在".$config[webname]."上发布的一个资源请求有了一个新回复。请<a href='".$config[weburl]."/qiu.php?show=".$qiu_id."'>点击此处查看</a>。</p>";
			if($reply_mail){
				$html .="<p>您也可以与回复者联系，他的邮箱地址为：<a href='mailto:".$reply_mail."'>".$reply_mail."</a></p>";
			}
			$html .="<p><a href='".$config[weburl]."'>".$config[webname]."团队</a></p>";
			
			return $this->sendmail($config[smtp][server],$config[smtp][port],$config[smtp][auth],$config[smtp][name],$config[smtp][password],$qiu_mail,$subject,$html);
		}
	}
	/* utility functions */
	
	public function tmpfilepath(){
		return dirname(__FILE__)."/../".$this->getFileRootDirectory()."/".$this->id_create("tmpfile").".tmp";
	}
	public function image_resize($path_img,$width,$height,$path_img_dest,$ratio=null){
		if($path_img && $path_img_dest){
			$img_type = $this->image_type($path_img);
			if($img_type==IMG_GIF){
				$img = imagecreatefromgif($path_img);
			}elseif($img_type==IMG_PNG){
				$img = imagecreatefrompng($path_img);
			}elseif($img_type==IMG_JPG){
				$img = imagecreatefromjpeg($path_img);
			}
			$size = getimagesize($path_img);
			if($ratio=="w" && $width){
				if($width>$size[0]){//只有当目标图片小于原始图片时才需要裁剪
					return copy($path_img,$path_img_dest);
				}
				$height = (int)(($width*$size[1])/$size[0]);
			}else if($ratio="h" && $height){
				if($height>$size[1]){//只有当目标图片小于原始图片时才需要裁剪
					return copy($path_img,$path_img_dest);
				}
				$width = (int)(($height*$size[0])/$size[1]);
			}else if(!$width || !$height){
				$this->log->error("width and height must be setted both.");
				return false;
			}
			if(function_exists("imagecreatetruecolor")){
				$img2 = imagecreatetruecolor($width,$height);
			}else{
				$img2 = imagecreate($width,$height);
			}
			if(function_exists("imagecopyresampled")){
				$res = imagecopyresampled($img2,$img,0,0,0,0,$width,$height,$size[0],$size[1]);
			}else{
				$res = imagecopyresized($img2,$img,0,0,0,0,$width,$height,$size[0],$size[1]);
			}
			if($res){
				return imagejpeg($img2,$path_img_dest,100);
			}
			return false;
		}
	}
	public function v_password($pwd){
		if(util::length($pwd)<6 || util::length($pwd)>40){
			return "密码长度应在6到40位";
		}
		return true;
	}
	public function date_now_to_int(){
		return time();
	}
	public function date_int_to_array($dateint){
		return getdate($dateint);
	}
	public function date_array_to_int($array){
		return mktime($array['hours'],$array['minutes'],$array['seconds'],$array['month'],$array['mday'],$array['year']);
	}
	public function date_string_to_int($datestr){
		return strtotime($datestr);
	}
	public function date_int_to_string($dateint,$format='Y-m-d H:i:s'){
		return date($format,$dateint);
	}
	public function id_create($type=""){
//$this->log->debug("======== start =========");
		$id = util::randID();
//$this->log->debug("id=".$id);
		$res = $this->db->query_first("select count(*) from t_id_record where id='$id'");
		if($res===false){//读取数据库失败，返回false
//$this->log->debug("读取数据库失败，返回false");
			return false;
		}

		if($res===1){//已经存在，重新生成
//$this->log->debug("已经存在，重新生成");
			return $this->id_create($type);
		}
//$this->log->debug("记录ID");
		$res2 = $this->db->update("insert into t_id_record(id,type,ctime) values('$id','$type',".time().")");//记录ID
		if($res2){
			return $id;
		}else{
//$this->log->debug("保存到数据库失败");
			return false;//保存到数据库失败
		}
	}
	public function vcode_make(){
		$vcode = util::randID();
		$_SESSION[vcode]=$vcode;
		return $vcode;
	}
	public function vcode_check($vcode){
		return $_SESSION[vcode] && $vcode==$_SESSION[vcode];
	}
	
	public function feeds_nav($url,$page,$pagesize,$total){
		$html = "";
		if(!strpos($url, '?')){
			$url.='?1=1';
		}
		$totalpage = intval(ceil($total/$pagesize));
		if($totalpage>=2){
			if($totalpage<=5){
				for($k=1;$k<=$totalpage;$k++){
					if($k==$page){
						$html.="<a class='p_s' href='$url&page=$k'>".$k."</a>";
					}else{
						$html.="<a href='$url&page=$k'>".$k."</a>";
					}
				}
			}else{
				if($page-1>2){
					$html.="<a href='$url&page=1'>1</a><span>...</span>";
				}
				for($k=$page-2;$k<=$page;$k++){
					if($k<1)continue;
					if($k==$page){
						$html.="<a class='p_s' href='$url&page=$k'>".$k."</a>";
					}else{
						$html.="<a href='$url&page=$k'>".$k."</a>";
					}
				}
				for($k=$page+1;$k<=$totalpage;$k++){
					if($k-$page<=2){
						$html.="<a href='$url&page=$k'>".$k."</a>";
					}
				}
				if($totalpage-$page>2){
					$html.="<span>...</span><a href='$url&page=$totalpage'>".$totalpage."</a>";
				}
			}
			if($page>1){
				$prepage = $page-1;
				$html="<a href='$url&page=$prepage'>上一页</a>".$html;
			}
			if($page<$totalpage){
				$nextpage = $page+1;
				$html=$html."<a href='$url&page=$nextpage'>下一页</a>";
			}
		}
		return $html;
	}
}
?>